package com.example.drive_safe;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ExclusionListActivity extends Activity {

	private static final int CONTACT_PICKER_RESULT = 1001;
	private SharedPreferences sharedPrefs = null;
	private Set<String> contacts = null;
	private List<String> data = null;
	private CustomContactAdapter adapter;
	
	@Override
	//initialize exclusion_list activity
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exclusion_list);
		this.sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		final ListView listview = (ListView) findViewById(R.id.exclListView);

		if (this.contacts == null) { 
			this.contacts = this.sharedPrefs.getStringSet("exclContacts", null);
		}
		
		if(this.contacts == null) {	// If the activity is loaded for the first time
			this.contacts = new HashSet<String>();
			this.data = new ArrayList<String>();
		}
		this.data = new ArrayList<String>(this.contacts);
		
		//calls CustomContactAdapter method  
		this.adapter = new
		CustomContactAdapter(this, this.data);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				data.remove(position);
	            contacts = new HashSet<String>(data);
	            save();
	            adapter.notifyDataSetChanged();
			}
		});
	}


	// implementation of exclusion contact list by extending ArrayAdapter 
	private class CustomContactAdapter extends ArrayAdapter<String> {
		private final Context context;
		private final List<String> data;
		
		public CustomContactAdapter(Context context, List<String> data) {
			super(context, R.layout.excl_contact_layout, data);
			this.context = context;
			this.data = data;
		}
		
		// Populate view from excl_contact_layout.xml file
		@Override
		  public View getView(int position, View convertView, ViewGroup parent) {
		    LayoutInflater inflater = (LayoutInflater) context
		        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    View rowView = inflater.inflate(R.layout.excl_contact_layout, parent, false);
		    TextView textView = (TextView) rowView.findViewById(R.id.singleContact);
		    textView.setText(this.data.get(position));
		    
		    return rowView;
		  }
	}
    
	// Launch contact picker to pick contacts from the contact list
	public void doLaunchContactPicker(View view) {
		Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
				Contacts.CONTENT_URI);
		startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
	}

	// Populating exclusion list by searching contacts from the phone's contact list
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CONTACT_PICKER_RESULT:
				if(this.contacts.size() <= 1000) { 		// replace 1000 with this.contacts.size() <= # if max exclusion list needs to be implemented
					Uri result = data.getData(); 		// this is line 71	// get the phone number id from uri
					String id = result.getLastPathSegment();
					Set<String> phoneNumbers = new HashSet<String>();
					String contact = null;
					
					// Query the phone number for the selected phone number id
					Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);
					int phoneIdx = cursor.getColumnIndex(Phone.NUMBER);
					int nameIdx = cursor.getColumnIndex(Phone.DISPLAY_NAME);
					if (cursor.moveToFirst()) {
	                    while (cursor.isAfterLast() == false) {
	                        phoneNumbers.add(cursor.getString(phoneIdx));
	                        contact = cursor.getString(nameIdx);
	                        cursor.moveToNext();
	                    }
	                }
					saveContact(contact, phoneNumbers);
				} else {
					// Show max contacts reached dialogue
				}
				break;
			}
		} else {
			// gracefully handle failure
		}
	}

	
	// Save all the contacts that are selected from the contact list in the exclusion list 
	private void saveContact(String contact, Set<String> phoneNumbers) {
		if (this.contacts == null) {
			this.contacts = new HashSet<String>();
		}
		if(!this.isDuplicate(contact)) {
			String stringToSave = contact + ":";
			for (String number : phoneNumbers) {
				stringToSave += this.format(number)+"/";	// separate the phone numbers with a '/' character
			}
			Log.d("StringToSave", stringToSave);
			this.contacts.add(stringToSave);
			this.save();
			this.data.add(stringToSave);
			this.adapter.notifyDataSetChanged();
		}
	}

	// Check if the contact already exists in the current list
	private boolean isDuplicate(String contact) {
		
		for(String existingContact:this.contacts) {
			if(existingContact.substring(0, existingContact.indexOf(":")).equals(contact))
				return true;
		}
		return false;		
	}

	// Format the number to a specific format
	private String format(String number) {
		// phone number can contain blank space, dashes, parentheses etc. see if
		// we need them. If not, remove them here
		return number;
	}
	
	// Save the contacts in the Exclusion list  
	private void save() {
		Editor editor = this.sharedPrefs.edit();//enables the editing option in the shared preference
		editor.putStringSet("exclContacts", this.contacts);
		editor.commit();
	}
}
